<script setup>
import axios from 'axios';
import { MessagePlugin } from 'tdesign-vue-next';
const baseUrl = import.meta.env.VITE_APP_API_BASE_URL
import { ref, reactive, computed } from 'vue';

import { inject } from 'vue';

const router = inject('router');
// export default {
//     setup() {
const form = ref(null);
const formData = reactive({
    username: '',
    password: '',
    email: '',
    mobile: '',
    rePassword: '',
});

const rePassword = (val) =>
    new Promise((resolve) => {
        const timer = setTimeout(() => {
            resolve(formData.password === val);
            clearTimeout(timer);
        }, 1000); // 假设验证延时为1秒
    });

const rules = {
    username: [
        { required: true, message: '用户名必填', type: 'error' },
        {
            min: 3,
            message: '至少需要两3个字符',
            type: 'error',
            trigger: 'blur',
        },
        {
            max: 32,
            message: '最长不能超过32个字符',
            type: 'error',
            trigger: 'blur',
        },
    ],

    password: [
        { required: true, message: '密码必填', type: 'error' },
    ],

    repassword: [
        { required: true, message: '密码必填', type: 'error' },
        { validator: rePassword, message: '两次密码不一致' }

    ]

};

const emailSuffix = ['@qq.com', '@163.com', "@189.cn", "@139.cn", '@gmail.com'];
const emailOptions = computed(() => {
    const emailPrefix = formData.email.split('@')[0];
    if (!emailPrefix)
        return [];
    return emailSuffix.map((suffix) => emailPrefix + suffix);
});

const onRegister = (validateResult, firstError) => {
    if (validateResult.firstError != "") {
        MessagePlugin.warning(validateResult.firstError);
    }


    if (validateResult.validateResult === true) {
        const url = baseUrl + '/user/register'
        console.log(url)
        axios.post(url, formData).then(res => {
            console.log(res.data);
            if (res.data.data.hasUser) {
                MessagePlugin.warning('该用户已经存在，请直接登录或更换用户名');
            }

            if (res.data.data == 'success') {
                MessagePlugin.success(res.data.msg);
                router.push("/userLogin")
            }


        }).catch(err => {
            MessagePlugin.error('用户注册失败，错误信息' + err);

            console.log("err:", err)
        })
    }
};

//         return {
//             form,
//             formData,
//             rules,
//             onRegister,
//             emailOptions
//         }
//     }
// }

</script>

<template>
    <div class="flex flex-col w-full bg-white w-max-md justify-center">


        <t-space direction="vertical" size="md" class="p-4">
            <t-form ref="form" :data="formData" reset-type="initial" :rules="rules" @reset="onReset" @submit="onRegister">
                <h1 class="text-xl p-4 font-bold mb-4 text-gray-900">{{ title }}</h1>

                <t-form-item label="用户名" name="username">
                    <t-input v-model="formData.username">
                        <template #prefix-icon>
                            <t-icon name="user" />
                        </template>
                    </t-input>
                </t-form-item>

                <t-form-item label="密码" name="password">
                    <t-input type="password" v-model="formData.password">
                        <template #prefix-icon>
                            <t-icon name="lock-on" />
                        </template>
                    </t-input>
                </t-form-item>

                <t-form-item label="重复密码" name="repassword">
                    <t-input type="password" v-model="formData.repassword">
                        <template #prefix-icon>
                            <t-icon name="lock-on" />
                        </template>
                    </t-input>
                </t-form-item>

                <t-form-item label="邮箱" name="email">
                    <!-- <t-input type="text" v-model="formData.email"> -->
                    <t-auto-complete v-model="formData.email" :options="emailOptions" filterable>
                        <template #prefix-icon>
                            <t-icon name="mail" />
                        </template>
                    </t-auto-complete>
                    <!-- </t-input> -->
                </t-form-item>

                <t-form-item label="手机" name="mobile">
                    <t-input type="text" v-model="formData.mobile">
                        <template #prefix-icon>
                            <t-icon name="mobile" />
                        </template>
                    </t-input>
                </t-form-item>

                <div class="flex flex-row justify-center gap-x-8">

                    <t-button type="submit" theme="primary">注册</t-button>
                    <t-button type="reset" variant="outline">重置</t-button>

                </div>
            </t-form>

        </t-space>
    </div>
</template>